package com.tbb.app.common.service.impl;

import com.tbb.app.common.entity.UserInfo;
import com.tbb.app.common.exception.BusinessException;
import com.tbb.app.common.exception.CommonCode;
import com.tbb.app.common.service.CacheService;
import com.tbb.app.common.service.TokenService;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * @author LiuSenLin
 * @date 2020/1/16
 */
@Slf4j
@Service
@AllArgsConstructor
@NoArgsConstructor
public class TokenServiceImpl implements TokenService {

    @Autowired
    private CacheService cacheService;

    @Override
    public UserInfo getUserInfo(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(CommonCode.C00002);
        }
        UserInfo userInfo = cacheService.get(token, UserInfo.class);
        if (userInfo == null) {
            throw new BusinessException(CommonCode.C00002);
        }
        cacheService.set(token, userInfo);
        return userInfo;
    }

    @Override
    public String generateAccessToken(UserInfo userInfo) {
        String uuid = UUID.randomUUID().toString();
        cacheService.set(uuid, userInfo);
        return uuid;
    }

    @Override
    public void removeToken(String token) {
        cacheService.delete(token);
    }

}
